/**
 * 
 */
package com.csair.youth.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.csair.youth.constant.Constant;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author mickey
 *
 */
public class LoginInterceptor extends AbstractInterceptor {

	private String noLoginUrlList = "";
	private boolean enable = false;

	public String[] getNoLoginUrlList() {
		if(StringUtils.isNotEmpty(noLoginUrlList)){
			String urls[] = noLoginUrlList.split(",");
			return urls;
		}
		else return null;
	}

	public void setNoLoginUrlList(String noLoginUrlList) {
		this.noLoginUrlList = noLoginUrlList;
	}
	
	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ctx = invocation.getInvocationContext();
		ActionProxy proxy = invocation.getProxy();
		Map session = ctx.getSession();
		String namespace = proxy.getNamespace();
		if(!namespace.endsWith("/")){
			namespace += "/";
		}
		if(!isEnable() || isUrlDoNotUseToLogin(namespace+proxy.getActionName(), getNoLoginUrlList())){
			if((namespace+proxy.getActionName()).equals("/Login") && session.get(Constant.USER_ID_SESSION_KEY) != null){
				return "home";
			}
			return invocation.invoke();
		}
		if(session.get(Constant.USER_ID_SESSION_KEY) != null){
			if((namespace+proxy.getActionName()).equals("/Login")){
				return "home";
			}
			return invocation.invoke();
		}
		else{
			//先将redirect的url写到session里面...
			String url = namespace+proxy.getActionName();
			HttpServletRequest req = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
			String queryString = req.getQueryString();
			if(!StringUtils.isEmpty(queryString)){
				url = url + "?" + queryString;
			}
			session.put(Constant.REDIRECT_URL_KEY, url);
			return "login";
		}
	}

	private boolean isUrlDoNotUseToLogin(String url, String[] list){
		if(list == null || list.length == 0) return false;
		else{
			for(int i=0; i<list.length; i++){
				if(list[i].equalsIgnoreCase(url)) return true;
			}
			return false;
		}
	}
}
